package com.meirengu.webview.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.meirengu.common.RedisClient;
import com.meirengu.utils.DateUtils;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.NumberUtil;
import com.meirengu.webview.model.*;
import com.meirengu.webview.service.*;
import com.meirengu.webview.utils.UserAgentRandomUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.meirengu.webview.common.ConfigConsts.CHANNEL_CODE_KAISEN2;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.time.DateUtils.addDays;
import static org.apache.commons.lang3.time.DateUtils.parseDate;


@Service
public class AsyncServiceImpl implements AsyncService {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private KwOperationLogService kwOperationLogService;
    @Autowired
    private UserService userService;
    @Autowired
    private KwHnbPushService kwHnbPushService;
    @Autowired
    private KwCyphFilterService kwCyphFilterService;
    @Autowired
    private KwXbbFilterService kwXbbFilterService;
    @Autowired
    private KwAreaDataService kwAreaDataService;
    @Autowired
    private KwZhudaiFilterService kwZhudaiFilterService;
    @Autowired
    private KwDfrzFilterService kwDfrzFilterService;
    @Autowired
    private KwXbbPushService kwXbbPushService;
    @Autowired
    private KwCyphPushService kwCyphPushService;
    @Autowired
    private KwPpdFilterService kwPpdFilterService;
    @Autowired
    private KwPpdPushService kwPpdPushService;
    @Autowired
    private LmUserService lmUserService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private KwWxInteractiveService kwWxInteractiveService;
    @Autowired
    private HyWxSubscribeService hyWxSubscribeService;
    @Autowired
    private KwFjsFilterService kwFjsFilterService;
    @Autowired
    private LmUserBaseService lmUserBaseService;
    @Autowired
    private ProductQualificationService productQualificationService;


    Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);


    @Override
    @Async
    public void sendMQAsync(String userId) {
        try {
            /*userInfoService.sendMQlinkwechat(userId);*/
            userInfoService.sendMQlinkMarketing(userId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.error(">> AsyncServiceImpl.sendMQAsync throw exception: {}", e);
        }

    }


    @Override
    @Async
    public void sendCyis(Integer delayDays) {
        try {
            Date currentDate = new Date();
            //当天开始时间
            Date dayBeginTime = DateUtils.getDayBeginTime(currentDate);
            //当天结束时间
            Date dayEndTime = DateUtils.getDayEndTime(currentDate);
            Date createTimeBegin = addDays(dayBeginTime, -delayDays.intValue());
            Date createTimeEnd = addDays(dayEndTime, -delayDays.intValue());
            //查出符合条件的用户
            Map<String, Object> map = new HashMap<>();
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<Map<String, Object>> userList = userService.getList(map);
            kwOperationLogService.addOperationLog("1", " 推送渠道", "sendCyis",
                    "定时发送畅愿保险数据", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "kw_user", userList.size(),
                    null, null, null);
            if (userList != null && userList.size() > 0) {
                for (Map<String, Object> userMap : userList) {
                    String id = userMap.get("id").toString();
                    if (userMap.get("name") != null) {
                        //校验是否有发送黑牛成功的记录
                        Map<String, Object> hnbparams = new HashMap<>();
                        hnbparams.put("mobile", userMap.get("mobile").toString());
                        hnbparams.put("code", 1);
                        Integer hnbpushCount = kwHnbPushService.getCount(hnbparams);
                        if (!NumberUtil.isNullOrZero(hnbpushCount)) {
                            continue;
                        }
                        UserInfo userInfo = userInfoService.getByUserId(id);
                        if (userInfo != null && isNotBlank(userInfo.getId())) {
                            User user = new User();
                            user.setId(id);
                            user.setName(userMap.get("name").toString());
                            user.setMobile(userMap.get("mobile").toString());
                            user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                            if (userMap.get("userAgent") != null) {
                                user.setUserAgent(userMap.get("userAgent").toString());
                            }
                            userInfo.setCreateDate(new Date());
                            kwCyphFilterService.sendChangYuanInsure(userInfo, user);
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.error(">> ScheduleController.sendCyis throw exception: {}", e);

        }
    }

    /**
     * 发送东方融资网数据
     *
     * @throws Exception
     */
    @Override
    @Async
    public void sendDfrz() {
        try {
            //查询当日记录
            Date currentDate = new Date();
            //当天开始时间
            Date dayBeginTime = DateUtils.getDayBeginTime(currentDate);
            //当天结束时间
            Date dayEndTime = DateUtils.getDayEndTime(currentDate);
            Date createTimeBegin = addDays(dayBeginTime, -3);
            Date createTimeEnd = addDays(dayEndTime, -3);
            //查出符合条件的用户
            Map<String, Object> map = new HashMap<>();
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<Map<String, Object>> userList = userService.getList(map);
            kwOperationLogService.addOperationLog("1", " 推送渠道", "sendDfrz",
                    "定时发送东方融资网数据", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "kw_user", userList.size(),
                    null, null, null);
            if (userList != null && userList.size() > 0) {
                for (Map<String, Object> userMap : userList) {
                    String id = userMap.get("id").toString();
                    if (userMap.get("name") != null) {
                        UserInfo userInfo = userInfoService.getByUserId(id);
                        if (userInfo != null && isNotBlank(userInfo.getId())) {
                            User user = new User();
                            user.setId(id);
                            user.setName(userMap.get("name").toString());
                            user.setMobile(userMap.get("mobile").toString());
                            user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                            kwDfrzFilterService.sendEastFinance(userInfo, user);
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.error(">> ScheduleController.sendDfrz throw exception: {}", e);
        }

    }

    @Override
    @Async
    public void sendXbb3(int amount) {
        try {
            String startDateMillis = redisClient.hget("pushTime", "sendXbb3");
            if (isBlank(startDateMillis)) {
                Date date = parseDate("20171221", "yyyyMMdd");
                startDateMillis = date.getTime() + "";
            }
            Date startDate = new Date(Long.parseLong(startDateMillis));
            //当天开始时间
            Date dayBeginTime = DateUtils.getDayBeginTime(startDate);
            //当天结束时间
            Date dayEndTime = DateUtils.getDayEndTime(startDate);
            Date createTimeBegin = dayBeginTime;
            Date createTimeEnd = addDays(dayEndTime, amount);
            String nextStartDateMillis = (addDays(dayBeginTime, amount + 1)).getTime() + "";
            redisClient.hset("pushTime", "sendXbb3", nextStartDateMillis);
            Map<String, Object> map = new HashMap<>();
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<Map<String, Object>> userList = userService.getList(map);
            kwOperationLogService.addOperationLog("1", " 定时任务", "handXbb3",
                    "定时发送新旦3数据", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "kw_user", userList.size(),
                    null, null, null);
            if (userList != null && userList.size() > 0) {
                for (Map<String, Object> userMap : userList) {
                    String id = userMap.get("id").toString();
                    if (userMap.get("name") != null) {
                        UserInfo userInfo = userInfoService.getByUserId(id);
                        if (userInfo != null && isNotBlank(userInfo.getId())) {
                            User user = new User();
                            user.setId(id);
                            user.setName(userMap.get("name").toString());
                            user.setMobile(userMap.get("mobile").toString());
                            user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                            if (userMap.get("userAgent") == null || isBlank(userMap.get("userAgent").toString())) {
                                user.setUserAgent(UserAgentRandomUtil.random());
                            } else {
                                user.setUserAgent(userMap.get("userAgent").toString());
                            }
                            kwXbbFilterService.sendXbb3(userInfo, user);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.error(">> ScheduleController.sendXbb3 throw exception: {}", e);
        }

    }


    @Override
    @Async
    public void sendXbb3Channel() {
        try {
            Map<String, Object> map = new HashMap<>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //获取前月的第一天
            Calendar cal_1 = Calendar.getInstance();//获取当前日期
            cal_1.add(Calendar.MONTH, -1);
            cal_1.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
            String createTimeBegin = format.format(DateUtils.getDayBeginTime(cal_1.getTime()));
            //获取前月的最后一天
            Calendar cale = Calendar.getInstance();
            cale.set(Calendar.DAY_OF_MONTH, 0);//设置为1号,当前日期既为本月第一天
            String createTimeEnd = format.format(DateUtils.getDayEndTime(cale.getTime()));
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<LmUser> userList = lmUserService.getModel(map);
            kwOperationLogService.addOperationLog("1", " 推送渠道", "handThirdChannelXbb3",
                    "手工发送第三方数据新旦3接口", createTimeBegin, createTimeEnd, "kw_user", userList.size(),
                    null, null, null);
            if (userList.size() > 0) {
                A:
                for (LmUser lmUser : userList) {
                    if (isNotBlank(lmUser.getName()) && isNotBlank(lmUser.getPhone())) {
                        Map<String, Object> baseMap = new HashMap<>();
                        baseMap.put("userId", lmUser.getId());
                        List<LmUserBase> list = lmUserBaseService.getModel(baseMap);
                        if (list.size() == 1) {
                            String channelCode = list.get(0).getChannelCode();
                            if ("dp_cy_001".equals(channelCode) || "dp_cy_002".equals(channelCode)) {
                                continue A;
                            }
                        }
                        lmUser.setCreateDate(new Date());
                        kwXbbFilterService.sendXbb3ByModel(lmUser);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">>handController.handThirdChannelXbb3 throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
        }
    }

    @Override
    @Async
    public void sendMdzjYiJuFz() {
        try {
            Map<String, Object> map = new HashMap<>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //获取前月的第一天
            Calendar cal_1 = Calendar.getInstance();//获取当前日期
            cal_1.add(Calendar.MONTH, -1);
            cal_1.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
            String createTimeBegin = format.format(DateUtils.getDayBeginTime(cal_1.getTime()));
            //获取前月的最后一天
            Calendar cale = Calendar.getInstance();
            cale.set(Calendar.DAY_OF_MONTH, 0);//设置为1号,当前日期既为本月第一天
            String createTimeEnd = format.format(DateUtils.getDayEndTime(cale.getTime()));
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<LmUser> userList = lmUserService.getModel(map);
            kwOperationLogService.addOperationLog("1", " 推送渠道", "sendMdzjYiJuFz",
                    "手工发送第三方数据熠巨方正", createTimeBegin, createTimeEnd, "lm_user", userList.size(),
                    null, null, null);
            if (userList.size() > 0) {
                A:
                for (LmUser lmUser : userList) {
                    if (isNotBlank(lmUser.getName()) && isNotBlank(lmUser.getPhone())) {
                        Map<String, Object> baseMap = new HashMap<>();
                        baseMap.put("userId", lmUser.getId());
                        List<LmUserBase> list = lmUserBaseService.getModel(baseMap);
                        if (list.size() == 1) {
                            String channelCode = list.get(0).getChannelCode();
                            if ("dp_cy_001".equals(channelCode) || "dp_cy_002".equals(channelCode)) {
                                continue A;
                            }
                        }
                        lmUser.setCreateDate(new Date());
                        kwFjsFilterService.sendMdzjYiJuFz(lmUser);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">>handController.handThirdChannelXbb3 throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
        }
    }

    @Override
    @Async
    public void sendPpdsu2(int amount) {
        try {
            String startDateMillis = redisClient.hget("pushTime", "sendPpdsu2");
            if (StringUtils.isBlank(startDateMillis)) {
                Date date = org.apache.commons.lang3.time.DateUtils.parseDate("20180411", "yyyyMMdd");
                startDateMillis = date.getTime() + "";
            }
            Date startDate = new Date(Long.parseLong(startDateMillis));
            //当天开始时间
            Date dayBeginTime = DateUtils.getDayBeginTime(startDate);
            //当天结束时间
            Date dayEndTime = DateUtils.getDayEndTime(startDate);
            Date createTimeBegin = dayBeginTime;
            Date createTimeEnd = org.apache.commons.lang3.time.DateUtils.addDays(dayEndTime, amount);
            String nextStartDateMillis = (org.apache.commons.lang3.time.DateUtils.addDays(dayBeginTime, amount + 1)).getTime() + "";
            redisClient.hset("pushTime", "sendPpdsu2", nextStartDateMillis);
            Map<String, Object> map = new HashMap<>();
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<Map<String, Object>> userList = userService.getList(map);
            kwOperationLogService.addOperationLog("1", "推送渠道", "sendPpdsu2",
                    "定时任务旧数据发送拍拍贷老用户接口", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "kw_user", userList.size(),
                    null, null, null);
            if (userList != null && userList.size() > 0) {
                for (Map<String, Object> userMap : userList) {
                    String id = userMap.get("id").toString();
                    if (userMap.get("name") != null) {
                        UserInfo userInfo = userInfoService.getByUserId(id);
                        if (userInfo != null && StringUtils.isNotBlank(userInfo.getId()) && StringUtils.isNotBlank(userInfo.getIdCard())) {
                            //校验是否有拍拍贷发送成功的记录
                            Map<String, Object> ppdparams = new HashMap<>();
                            ppdparams.put("mobile", userMap.get("mobile").toString());
                            ppdparams.put("code", 1);
                            Integer ppdPushCount = kwPpdPushService.getCount(ppdparams);
                            //已有成功发送记录
                            if (!NumberUtil.isNullOrZero(ppdPushCount)) {
                                continue;
                            }
                            User user = new User();
                            user.setId(id);
                            user.setName(userMap.get("name").toString());
                            user.setMobile(userMap.get("mobile").toString());
                            user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                            kwPpdFilterService.sendPpdaiBySleepingUser2(userInfo, user);
                        }
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">>handController.handThirdChannelXbb3 throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
        }
    }

    private final String fieldSendKaise2 = "sendKaisen2";

    @Override
    @Async
    public void sendKaisen2(int amount) {
        try {
            String startDateMillis = redisClient.hget("pushTime", fieldSendKaise2);
            if (isBlank(startDateMillis)) {
                Date date = parseDate("20180601", "yyyyMMdd");
                startDateMillis = date.getTime() + "";
            }
            Date startDate = new Date(Long.parseLong(startDateMillis));
            //当天开始时间
            Date dayBeginTime = DateUtils.getDayBeginTime(startDate);
            //当天结束时间
            Date dayEndTime = DateUtils.getDayEndTime(startDate);
            Date createTimeBegin = dayBeginTime;
            Date createTimeEnd = addDays(dayEndTime, amount);
            String nextStartDateMillis = (addDays(dayBeginTime, amount + 1)).getTime() + "";
            redisClient.hset("pushTime", fieldSendKaise2, nextStartDateMillis);
            Map<String, Object> map = new HashMap<>();
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<Map<String, Object>> userList = userService.getList(map);
            kwOperationLogService.addOperationLog("1", "推送渠道", fieldSendKaise2
                    , "定时任务旧数据发送凯森2老用户接口", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd)
                    , "kw_user", userList.size(), null, null, null);
            if (userList != null && userList.size() > 0) {
                for (Map<String, Object> userMap : userList) {
                    String id = userMap.get("id").toString();
                    if (userMap.get("name") != null) {
                        UserInfo userInfo = userInfoService.getByUserId(id);
                        if (userInfo != null && isNotBlank(userInfo.getId()) && isNotBlank(userInfo.getIdCard())) {
                            Map<String, Object> params = new HashMap<>();
                            params.put("mobile", userMap.get("mobile").toString());
                            params.put("code", 1);
                            params.put("channel_code", CHANNEL_CODE_KAISEN2);
                            Integer ppdPushCount = kwCyphFilterService.getCount(params);
                            //已有成功发送记录
                            if (!NumberUtil.isNullOrZero(ppdPushCount)) {
                                continue;
                            }
                            User user = new User();
                            user.setId(id);
                            user.setName(userMap.get("name").toString());
                            user.setMobile(userMap.get("mobile").toString());
                            user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                            kwCyphFilterService.sendKaisen2(userInfo, user);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">>handController.handThirdChannelXbb3 throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
        }
    }

    @Override
    @Async
    public void sendXbbProduct(int amount) throws Exception {
        try {
            String startDateMillis = redisClient.hget("pushTime", "sendXbbProduct");
            if (isBlank(startDateMillis)) {
                Date date = parseDate("20190101", "yyyyMMdd");
                startDateMillis = date.getTime() + "";
            }
            Date startDate = new Date(Long.parseLong(startDateMillis));
            //当天开始时间
            Date dayBeginTime = DateUtils.getDayBeginTime(startDate);
            //当天结束时间
            Date dayEndTime = DateUtils.getDayEndTime(startDate);
            Date createTimeBegin = dayBeginTime;
            Date createTimeEnd = addDays(dayEndTime, amount);
            String nextStartDateMillis = (addDays(dayBeginTime, amount + 1)).getTime() + "";
            redisClient.hset("pushTime", "sendXbbProduct", nextStartDateMillis);
            Map<String, Object> map = new HashMap<>();
            map.put("createDateBegin", createTimeBegin);
            map.put("createDateEnd", createTimeEnd);
            map.put("phoneIsNotNull", "phoneIsNotNull");

            List<Map<String, Object>> userList = productQualificationService.getList(map);
            kwOperationLogService.addOperationLog("1", "推送渠道", "sendXbbProduct",
                    "定时发送新旦保险product数据", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "kw_user", userList.size(),
                    null, null, null);
            if (userList != null && userList.size() > 0) {
                for (Map<String, Object> userMap : userList) {
                    User user = new User();
                    user.setId(userMap.get("id").toString());
                    user.setName(userMap.get("name").toString());
                    user.setMobile(userMap.get("mobile").toString());
                    user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                    user.setUserAgent(UserAgentRandomUtil.random());
                    UserInfo userInfo = new UserInfo();
                    userInfo.setBirthday((Date) userMap.get("birthday"));
                    userInfo.setScity(userMap.get("areaName").toString());
                    if (userMap.get("idCard") != null) {
                        userInfo.setIdCard(userMap.get("idCard").toString());
                    }
                    userInfo.setHouse(Integer.parseInt(userMap.get("house").toString()));
                    userInfo.setCar(Integer.parseInt(userMap.get("car").toString()));
                    userInfo.setPolicy(Integer.parseInt(userMap.get("policy").toString()));
                    userInfo.setExpectAmount(new BigDecimal(userMap.get("expectAmount").toString()));
                    userInfo.setSalary(Integer.parseInt(userMap.get("salary").toString()));
                    userInfo.setIp(userMap.get("ip").toString());
                    kwXbbFilterService.sendXbb(userInfo, user);

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            String params = "";
            logger.error(">>handController.handThirdChannelXbb3 throw exception: {} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
        }
    }


    @Override
    @Async
    public void sendStockSMS() {
        try {
            //查询当日记录
            Date currentDate = new Date();
            //当天开始时间
            Date dayBeginTime = DateUtils.getDayBeginTime(currentDate);
            //当天结束时间
            Date dayEndTime = DateUtils.getDayEndTime(currentDate);
            Date createTimeBegin = org.apache.commons.lang3.time.DateUtils.addHours(dayBeginTime, -2);
            Date createTimeEnd = addDays(dayBeginTime, 9);
            kwOperationLogService.addOperationLog("2", "发送短信", "sendStockSMS",
                    "定时发送积压短信", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "redislist", 0,
                    null, null, null);
            userInfoService.sendStockSMS();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.error(">> ScheduleController.sendSms throw exception: {}", e);
        }
    }

    @Override
    @Async
    public void sendXbb2() {
        try {
            //查询当日记录
            Date currentDate = new Date();
            //当天开始时间
            Date dayBeginTime = DateUtils.getDayBeginTime(currentDate);
            //当天结束时间
            Date dayEndTime = DateUtils.getDayEndTime(currentDate);
            Date createTimeBegin = addDays(dayBeginTime, -5);
            Date createTimeEnd = addDays(dayEndTime, -5);
            //查出符合条件的用户
            Map<String, Object> map = new HashMap<>();
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<Map<String, Object>> userList = userService.getList(map);
            kwOperationLogService.addOperationLog("1", " 推送渠道", "sendXbb2",
                    "定时发送xbb2数据", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "kw_user", userList.size(),
                    null, null, null);
            if (userList != null && userList.size() > 0) {
                for (Map<String, Object> userMap : userList) {
                    String id = userMap.get("id").toString();
                    if (userMap.get("name") != null) {
                        UserInfo userInfo = userInfoService.getByUserId(id);
                        if (userInfo != null && isNotBlank(userInfo.getId())) {
                            User user = new User();
                            user.setId(id);
                            user.setName(userMap.get("name").toString());
                            user.setMobile(userMap.get("mobile").toString());
                            user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                            if (userMap.get("userAgent") != null) {
                                user.setUserAgent(userMap.get("userAgent").toString());
                            }
                            userInfo.setCreateDate(new Date());
                            kwXbbFilterService.sendXbbForPingan(userInfo, user);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.error(">> ScheduleController.sendXbb2 throw exception: {}", e);

        }
    }

    /**
     * 定时补发前一天由于渠道推
     * 送数量限制而未发送的数据
     *
     * @throws Exception
     *//*
    @Override
    @Async
    public void scheduleZhudaiPush() {
        try {
            Map<String, String> map = new HashMap<>();
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createTimeBegin = sdf.format(DateUtils.getDayBeginTime(calendar.getTime()));
            String createTimeEnd = sdf.format(DateUtils.getDayEndTime(calendar.getTime()));
            map.put("code", 9 + "");
            map.put("createTimeBegin", createTimeBegin);
            map.put("createTimeEnd", createTimeEnd);
            List<KwZhudaiFilter> zhudaiList = kwZhudaiFilterService.getModel(map);
            kwOperationLogService.addOperationLog("1", "补发助贷网数据", "scheduleZhudaiPush",
                    "补发助贷网数据", createTimeBegin, createTimeEnd, "kw_zhudai_push", zhudaiList.size(),
                    null, null, null);
            if (zhudaiList.size() > 0) {
                A:
                for (KwZhudaiFilter kwZhudaiFilter : zhudaiList) {
                    Map<String, Object> userMap = new HashMap<>();
                    userMap.put("mobile", kwZhudaiFilter.getMobile());
                    List<Map<String, Object>> userList = userService.getList(userMap);
                    if (userList != null && userList.size() > 0) {
                        B:
                        for (Map<String, Object> uMap : userList) {
                            String id = uMap.get("id").toString();
                            if (uMap.get("name") != null) {
                                UserInfo userInfo = userInfoService.getByUserId(id);
                                User user = new User();
                                user.setId(id);
                                user.setName(uMap.get("name").toString());
                                user.setMobile(uMap.get("mobile").toString());
                                user.setSex(Integer.parseInt(uMap.get("sex").toString()));
                                user.setCreateDate(sdf.parse(uMap.get("createDate").toString()));
                                if (uMap.get("userAgent") != null) {
                                    user.setUserAgent(uMap.get("userAgent").toString());
                                }
                                userInfo.setCreateDate(new Date());
                                kwZhudaiFilterService.sendZhuDai(userInfo, user);

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.error(">> ScheduleController.scheduleZhudaiPush throw exception: {}", e);
        }
    }*/


    /**
     * 每天五点推送信息给微信活跃用户
     */
    @Override
    @Async
    public void sendWxMsg() {
        try {
            //查询当日记录
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DATE, -1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String createDateBegin = sdf.format(c.getTime());
            String createDateEnd = sdf.format(new Date());
            createDateBegin = createDateBegin + " 17:00:00";
            createDateEnd = createDateEnd + " 16:59:59";
            Map<String, Object> map = new HashMap<>();
            System.out.println(createDateBegin);
            System.out.println(createDateEnd);
            map.put("createDateBegin", createDateBegin);
            map.put("createDateEnd", createDateEnd);
            List<KwWxInteractive> list = kwWxInteractiveService.getModel(map);
            kwOperationLogService.addOperationLog("1", " 微信推送", "sendWxMsg",
                    "每天五点推送信息给微信活跃用户", createDateBegin, createDateEnd, "kw_wx_interactive", list.size(),
                    null, null, null);
            if (list.size() > 0) {
                for (KwWxInteractive kwWxInteractive : list) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("touser", kwWxInteractive.getFromUserName());
                    jsonObject.put("msgtype", "text");
                    JSONObject contentJson = new JSONObject();
                    StringBuilder contentBuffer = new StringBuilder();
                    contentBuffer.append("芝麻分500=20000元！\n\n");
                    contentBuffer.append("你周围已有1563人成功下款!\n\n");
                    String accessToken = "";
                    if ("gh_3f1914b0864d".equals(kwWxInteractive.getToUserName())) {
                        contentBuffer.append("<a href=\"https://mdzj139.com/loan/index.html?cid=channel_wxtg1#/market\">点击拿钱</a>");
                        accessToken = redisClient.get("HGWXACCESSTOKEN");
                        System.out.println("黄瓜有钱");
                    } else if ("gh_895ae09a34b3".equals(kwWxInteractive.getToUserName())) {
                        contentBuffer.append("<a href=\"https://mdzj139.com/loan/index.html?cid=channel_wxtg#/market\">点击拿钱</a>");
                        accessToken = redisClient.get("WXACCESSTOKEN");
                        System.out.println("花花有钱");
                    } else if ("gh_1f6f426e35d1".equals(kwWxInteractive.getToUserName())) {
                        contentBuffer.append("<a href=\"https://mdzj139.com/loan/index.html?cid=channel_wxtg1#/market\">点击拿钱</a>");
                        accessToken = redisClient.get("HGWXACCESSTOKEN");
                        System.out.println("测试账号");
                    } else if ("gh_8793e67e61c8".equals(kwWxInteractive.getToUserName())) {
                        contentBuffer.append("<a href=\"https://mdzj139.com/loan/index.html?cid=channel_wx#/market\">点击拿钱</a>");
                        accessToken = redisClient.get("MFPWXACCESSTOKEN");
                        System.out.println("秒分配");
                    } else if ("gh_13ebf46e724c".equals(kwWxInteractive.getToUserName())) {
                        contentBuffer.append("<a href=\"https://mdzj139.com/loan/index.html?cid=channel_wx#/market\">点击拿钱</a>");
                        accessToken = redisClient.get("WKWXACCESSTOKEN");
                        System.out.println("玩卡钱包");
                    } else if ("gh_1607a31648b0".equals(kwWxInteractive.getToUserName())) {
                        contentBuffer.append("<a href=\"https://mdzj139.com/loan/index.html?cid=channel_wxtg5#/market\">点击拿钱</a>");
                        accessToken = redisClient.get("DIGUAWXACCESSTOKEN");
                        System.out.println("地瓜有钱");
                    } else if ("gh_d71301a42979".equals(kwWxInteractive.getToUserName())) {
                        contentBuffer.append("<a href=\"https://mdzj139.com/loan/index.html?cid=channel_wxtg7#/market\">点击拿钱</a>");
                        accessToken = redisClient.get("YJWXACCESSTOKEN");
                        System.out.println("应急现金贷");
                    } else if ("gh_56111e0e8374".equals(kwWxInteractive.getToUserName())) {
                        contentBuffer.append("<a href=\"https://mdzj139.com/loan/index.html?cid=channel_wxhghh#/market\">点击拿钱</a>");
                        accessToken = redisClient.get("HGHUAWXACCESSTOKEN");
                        System.out.println("黄瓜花花");
                    }
                    String contentStr = contentBuffer.toString();
                    contentJson.put("content", contentStr);
                    jsonObject.put("text", contentJson);
                    String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
                    HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
                    System.out.println(hr.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.error(">> ScheduleController.sendWxMsg throw exception: {}", e);
        }
    }

    @Override
    @Async
    public void sendTemplateMsgScheduled() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> map = new HashMap<>();
        map.put("toUserName", "gh_25e40b50f9b3");
        List<Map<String, Object>> userList = hyWxSubscribeService.getList(map);
        String openid = null;
        JSONObject dataJson = null;
        JSONObject first = null;
        JSONObject keyword1 = null;
        JSONObject keyword2 = null;
        JSONObject keyword3 = null;
        JSONObject remark = null;
        int count = 0;
        for (Map<String, Object> userMap : userList) {
            logger.info("count========>. count:{}", count++);
            openid = userMap.get("fromUserName").toString();
            jsonObject.put("touser", openid);
            jsonObject.put("template_id", "FkIWDJqq_k9bs9FHzX7-S5l_O5MypYLG-cnLQXSdbX4");
            jsonObject.put("url", "https://mdzj139.com/loan/index.html?cid=channel_wxtg6#/market");
            dataJson = new JSONObject();

            first = new JSONObject();
            first.put("value", "根据您的资质和情况，已符合贷款资格，额度10000-50000元");
            first.put("color", "#FF0000");
            dataJson.put("first", first);


            keyword1 = new JSONObject();
            keyword1.put("value", sdf.format(new Date()));
            keyword1.put("color", "#173177");
            dataJson.put("keyword1", keyword1);

            keyword2 = new JSONObject();
            keyword2.put("value", "10000-50000");
            keyword2.put("color", "#173177");
            dataJson.put("keyword2", keyword2);

            keyword3 = new JSONObject();
            keyword3.put("value", "7-30天");
            keyword3.put("color", "#173177");
            dataJson.put("keyword3", keyword3);

            remark = new JSONObject();
            StringBuilder contentBuffer = new StringBuilder();
            contentBuffer.append("点击立即申请>>>");
            String contentStr = contentBuffer.toString();
            remark.put("value", contentStr);
            remark.put("color", "#FF0000");
            dataJson.put("remark", remark);

            jsonObject.put("data", dataJson);

            /*String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=14_DhgdYNoEVjs2ajDbFpyrDF9V-Xaaq9GLd_iGYgocAWs_LyCMw0fDnjmV5ItLcrhUlnNnRqjoPZVdqH3w2QA4pa2mumB9gFuE_GnHifgXm_qPO7iCBwc4gPqtRCsHGRx4vIFL4oHUAzT-bS0FMVOfADAVEX";*/
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + redisClient.get("HYWXACCESSTOKEN");
            HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
            System.out.println(hr.toString());
        }
    }

    @Override
    @Async
    public void sendYiJu() throws Exception {
        //查询当日记录
        Date currentDate = new Date();
        //当天开始时间
        Date dayBeginTime = DateUtils.getDayBeginTime(currentDate);
        //当天结束时间
        Date dayEndTime = DateUtils.getDayEndTime(currentDate);
        Date createTimeBegin = addDays(dayBeginTime, -5);
        Date createTimeEnd = addDays(dayEndTime, -5);
        //查出符合条件的用户
        Map<String, Object> map = new HashMap<>();
        map.put("createTimeBegin", createTimeBegin);
        map.put("createTimeEnd", createTimeEnd);
        List<Map<String, Object>> userList = userService.getList(map);
        kwOperationLogService.addOperationLog("1", " 推送渠道", "sendYiJu",
                "定时发送熠巨数据", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "kw_user", userList.size(),
                null, null, null);
        if (userList != null && userList.size() > 0) {
            for (Map<String, Object> userMap : userList) {
                String id = userMap.get("id").toString();
                if (userMap.get("name") != null) {
                    UserInfo userInfo = userInfoService.getByUserId(id);
                    if (userInfo != null && isNotBlank(userInfo.getId())) {
                        User user = new User();
                        user.setId(id);
                        user.setName(userMap.get("name").toString());
                        user.setMobile(userMap.get("mobile").toString());
                        user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                        kwFjsFilterService.sendYiJu(userInfo, user);
                    }
                }

            }
        }
    }

    @Override
    @Async
    public void sendYiJuFz() throws Exception {
        //查询当日记录
        Date currentDate = new Date();
        //当天开始时间
        Date dayBeginTime = DateUtils.getDayBeginTime(currentDate);
        //当天结束时间
        Date dayEndTime = DateUtils.getDayEndTime(currentDate);
        Date createTimeBegin = addDays(dayBeginTime, -6);
        Date createTimeEnd = addDays(dayEndTime, -6);
        //查出符合条件的用户
        Map<String, Object> map = new HashMap<>();
        map.put("createTimeBegin", createTimeBegin);
        map.put("createTimeEnd", createTimeEnd);
        List<Map<String, Object>> userList = userService.getList(map);
        kwOperationLogService.addOperationLog("1", " 推送渠道", "sendYiJuFz",
                "定时发送熠巨方正数据", DateUtils.dateToStr(createTimeBegin), DateUtils.dateToStr(createTimeEnd), "kw_user", userList.size(),
                null, null, null);
        if (userList != null && userList.size() > 0) {
            for (Map<String, Object> userMap : userList) {
                String id = userMap.get("id").toString();
                if (userMap.get("name") != null) {
                    UserInfo userInfo = userInfoService.getByUserId(id);
                    if (userInfo != null && isNotBlank(userInfo.getId())) {
                        /*String areaCode = userInfo.getAreaCode() + "";
                        String regEx = "^[3][7]\\d{4}$";
                        boolean isMatch = Pattern.matches(regEx, areaCode);
                        if(isMatch) {*/
                        User user = new User();
                        user.setId(id);
                        user.setName(userMap.get("name").toString());
                        user.setMobile(userMap.get("mobile").toString());
                        user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                        kwFjsFilterService.sendYiJuFz(userInfo, user);
                        // }
                    }
                }

            }
        }
    }

}
